package net.maku.generator.controller;

import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import net.maku.generator.common.page.PageResult;
import net.maku.generator.common.utils.Result;
import net.maku.generator.config.template.TemplateInfo;
import net.maku.generator.domain.entity.ProjectEntity;
import net.maku.generator.domain.entity.TableEntity;
import net.maku.generator.domain.query.Query;
import net.maku.generator.domain.vo.PreviewVO;
import net.maku.generator.domain.vo.TreeVO;
import net.maku.generator.service.ProjectService;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 项目名变更
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("maku-generator/gen/project")
@AllArgsConstructor
public class ProjectController {

    private final ProjectService projectService;

    @GetMapping("page")
    public Result<PageResult<ProjectEntity>> page(@Valid Query query) {
        PageResult<ProjectEntity> page = projectService.page(query);

        return Result.ok(page);
    }

    @GetMapping("/list")
    public Result<List<ProjectEntity>> list() {
        List<ProjectEntity> list = projectService.list();
        return Result.ok(list);
    }

    @GetMapping("/table/list")
    public Result<List<TableEntity>> tableList(@RequestParam("projectId") Long projectId,
                                               @RequestParam(value = "tableName", required = false) String tableName) {
        List<TableEntity> list = projectService.tableList(projectId, tableName);
        return Result.ok(list);
    }

    @GetMapping("{id}")
    public Result<ProjectEntity> get(@PathVariable("id") Long id) {
        ProjectEntity entity = projectService.getById(id);
        return Result.ok(entity);
    }

    @PostMapping
    public Result<String> saveData(@RequestBody ProjectEntity entity) {
        projectService.saveData(entity);

        return Result.ok();
    }

    @PutMapping
    public Result<String> update(@RequestBody @Valid ProjectEntity entity) {
        projectService.updateById(entity);

        return Result.ok();
    }

    @DeleteMapping
    public Result<String> delete(@RequestBody List<Long> idList) {
        projectService.delete(idList);
        return Result.ok();
    }

    /**
     * 下载到服务器本地
     *
     * @param id
     * @return
     * @throws IOException
     */
    @GetMapping("/download/{id}")
    public Result<Void> download(@PathVariable("id") Long id) throws IOException {
        projectService.download(id);
        return Result.ok();
    }

    /**
     * 下载项目（压缩包）
     */
    @GetMapping("/download-zip/{id}")
    public void downloadZip(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        projectService.downloadZip(id, response);
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview")
    public Result<List<PreviewVO>> preview(@RequestParam("projectId") Long projectId) {
        List<PreviewVO> results = projectService.preview(projectId);
        return Result.ok(results);
    }

    /**
     * 树形数据
     */
    @GetMapping("/tree-data")
    public Result<List<TreeVO>> treeData(@RequestParam("projectId") Long projectId) {
        List<TreeVO> results = projectService.treeData(projectId);
        return Result.ok(results);
    }

    /**
     * 下载单个文件代码
     */
    @GetMapping("/download-template-content")
    public void download(@RequestParam("projectId") Long projectId,
                         @RequestParam("templateId") Long templateId,
                         @RequestParam("templateGroupType") Integer templateGroupType,
                         @RequestParam(value = "tableId", required = false) Long tableId,
                         HttpServletResponse response) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        TemplateInfo templateInfo = projectService.generatorCode(projectId, tableId, templateId, templateGroupType);

        outputStream.write(templateInfo.getTemplateData().getBytes());
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + templateInfo.getFileName());
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

}